import { useEffect, useState, useRef } from "react";
import "./style.less";
import { Button, Select, Space, notification, Tooltip } from "antd";
import { appOpt, signStatusDic } from "./helper";
import workImg from "@/assets/working.gif";
import sucessImg from "@/assets/sucess.gif";
import failedImg from "@/assets/failed.gif";
import { SmileOutlined } from '@ant-design/icons';

function Sign() {
  const [file, setFile] = useState();
  const [processMsgs, setProcessMsgs] = useState([]);
  const [signStatus, setSignStatus] = useState({ status: null, outPath: null });

  /**
   * 打开上传文件窗口
   */
  const onSelectFile = async () => {
    let res = await electronAPI.openFileDialog(["apk"]);
    setFile(res[0]);
  };

  const [carType, setCarType] = useState("wutong");
  const onCarTypeChange = (value) => {
    setCarType(value);
  };

  // 选择包名
  const [pkg, setPkg] = useState();
  const onPkgChange = (value) => {
    setPkg(value);
  };
  const processMsgsRef = useRef([]);
  const doCrack = async () => {
    setProcessMsgs([]);
    processMsgsRef.current = [];
    electronAPI.crackApk({
      filePath: file,
      carType,
      pkgName: pkg,
    });
  };

  const showExplorer = () => {
    electronAPI.showExplorer(signStatus.outPath);
  };

  const listRef = useRef(null);
  const scrollToLastMessage = () => {
    listRef.current.scrollTop = listRef.current.scrollHeight;
  };

  const onProcessMsg = (res) => {
    setSignStatus({ status: res.status, outPath: res.data.msg });
    // processMsgs.push(res.data.msg);
    // setProcessMsgs([...processMsgs]);
    processMsgsRef.current.push(res.data.msg);
    console.log(999999, processMsgsRef.current);
    setProcessMsgs(processMsgsRef.current);
    scrollToLastMessage();
  };

  const [copyStatus, setCopyStatus] = useState("复制");
  const doCopy = () => {
    const res = processMsgs.join('\n')
    electronAPI.copyToClipboard(res);
    setCopyStatus("已复制");
    setTimeout(() => {
      setCopyStatus("复制");
    }, 1000);
  };

  const [api, contextHolder] = notification.useNotification({bottom:6});
  const openNotification = () => {
    api.open({
      message: '复制成功',
      icon: <SmileOutlined style={{ color: '#108ee9' }} />,
      duration:1,
      placement: 'bottomRight'
    });
  };
  const doCopyPath = () => {
    electronAPI.copyToClipboard(signStatus.outPath);
    openNotification();
  }

  useEffect(() => {
    electronAPI.onProcessMsg(onProcessMsg);
  }, []);

  return (
    <div className="mt-2">
      {contextHolder}
      <div className="fileup" onClick={onSelectFile}>
        {file ? file : "请选择 安装包"}
      </div>

      <div className="carPkgType">
        <div className="carType">
          <label>车系：</label>
          <Select
            onChange={onCarTypeChange}
            defaultValue="wutong"
            className="carTypeSelect"
          >
            <Select.Option value="wutong">梧桐系</Select.Option>
            <Select.Option value="feiyu">飞鱼系</Select.Option>
            {/* <Select.Option value="g318">深蓝G318</Select.Option>
                <Select.Option value="a07">起源A07</Select.Option> */}
          </Select>
        </div>

        <div className="pkgType">
          <label>包名：</label>
          <Select
            onChange={onPkgChange}
            className="pkgSelect"
            options={appOpt}
            showSearch={true}
            allowClear={true}
            getPopupContainer={(triggerNode) => triggerNode.parentNode}
            mode="SECRET_COMBOBOX_MODE_DO_NOT_USE"
          />
        </div>

        <div className="text-center ml-6">
          <Space>
            <Button disabled={!file} type="primary" onClick={doCrack}>
              开始转换
            </Button>
            {signStatus.status === 2 && (
              <Button type="primary" onClick={showExplorer}>
                打开文件
              </Button>
            )}
          </Space>
        </div>
      </div>
      <div className="tips">注意：车系用于伪装签名、包名用于修改apk的package字段（慎选）</div>

      <div className="terminal-father">
        {processMsgs.length > 0 && (
          <div className="copy" onClick={doCopy}>
            {copyStatus}
          </div>
        )}

        <div className="terminal" ref={listRef}>
          {processMsgs.map((item, index) => (
            <div className="processMsg" key={index}>
              {item}
            </div>
          ))}
        </div>
      </div>

      <div className="result">
        {signStatus.status != null && (
          <>
            {signStatus.status == 0 && <img src={failedImg} />}
            {signStatus.status == 1 && <img src={workImg} />}
            {signStatus.status == 2 && <img src={sucessImg} />}
          </>
        )}
        <span>{signStatusDic[signStatus.status]}</span>
        {signStatus.status === 2 && (
          <Tooltip placement="right" title="点击复制">
            <span className="signPath" onClick={doCopyPath}>：{signStatus.outPath}</span>
          </Tooltip>
        )}
      </div>
    </div>
  );
}

export default Sign;
